//
//  SEGOrderHandleController.m
//  Uhomebk
//
//  Created by mac on 2017/7/11.
//  Copyright © 2017年 com.segi. All rights reserved.
//

#import "SEGOrderHandleController.h"
#import "ControlTemplateViewController.h"
#import "SEGOrderDetailManager.h"

@interface SEGOrderHandleController () <ControlTemplateViewControllerDelegate, UIScrollViewDelegate > {
    CustomButtonView* submitBtn;//提交按钮
    ControlTemplateViewController *templateVC;//生成所有控件的VC
    NSOperationQueue* queue;//线程队列
    NSInteger uploadPicNum; /**<上传图片的数量*/
    UIScrollView *bgScrollView;//背景View
    CGFloat nowY;
    NSString* deviceId; //设备计划ID
    NSString* patrolId; //巡更计划ID
}

@property (nonatomic, strong)NSMutableArray *dataArray; // 界面展示数据源

@end

@implementation SEGOrderHandleController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self setupUI];
    dispatch_async(dispatch_get_main_queue(), ^{
        [self refreshViews];
    });
}

#pragma mark - ================<视图初始化>===============
- (void)setupUI {
    [self showCustomNavigationBackButton];
    
    submitBtn = [[CustomButtonView alloc] init];
    submitBtn.titleLabel.font = kFont_16;
    submitBtn.backgroundColor = kColor_T;
    [submitBtn setBackgroundImage:[UIImage imageWithColor:kColor_T] forState:UIControlStateNormal];
    [submitBtn setBackgroundImage:[UIImage imageWithColor:kColor_T_Press] forState:UIControlStateHighlighted];
    [submitBtn addTarget:self action:@selector(submitOrderFormInfoAction) forControlEvents:UIControlEventTouchUpInside];
    submitBtn.contentEdgeInsets = UIEdgeInsetsMake(0, 0, LYSafeAreaBottom(), 0);
    [submitBtn setTitle:@"提交" forState:UIControlStateNormal];
    [self.view addSubview:submitBtn];
    [submitBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.bottom.right.equalTo(self.view);
        make.height.mas_equalTo(44 + LYSafeAreaBottom());
    }];
    
    bgScrollView = [[UIScrollView alloc] init];
    bgScrollView.delegate = self;
    bgScrollView.showsHorizontalScrollIndicator = NO;
    bgScrollView.showsVerticalScrollIndicator = NO;
    [self.view addSubview:bgScrollView];
    
    [bgScrollView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(0);
        make.left.right.equalTo(self.view);
        make.bottom.equalTo(submitBtn.mas_top);
    }];
}


-(void)refreshViews {
    //控件初始化
    if (templateVC) {
        templateVC = nil;
    }
    templateVC = [[ControlTemplateViewController alloc] init];
    templateVC.fundelegate = self;
    templateVC.mastVC = self;
    templateVC.communityId = _detailModel.baseInfos.organId;
    templateVC.orderId = _detailModel.baseInfos.organId;
    
    //控件展示
    [self showTemplateView];
}


/**
 展示控件
 */
-(void)showTemplateView {
    [self.dataArray removeAllObjects];
    for (SEGTemplateModel *templateModel in  _actionModel.formList) {
        NSDictionary *dic = templateModel.mDictionary;
        [dic setValue:_detailModel.baseInfos.templateType forKey:@"templateType"];
        //加入其它参数
        [dic setValue:_detailModel.baseInfos.serviceOrderId forKey:@"serviceOrderId"];
        [dic setValue:_detailModel.baseInfos.trackId forKey:@"trackId"];
        [dic setValue:_detailModel.baseInfos.organId forKey:@"communityId"];
        [dic setValue:_detailModel.baseInfos.serviceOrderId forKey:@"id"];
        [_dataArray addObject:dic];
    }
    
    //生成控件
    [templateVC onCreateTemplateWithHandleType:_actionModel.actionCode dataArr:_dataArray view:bgScrollView];
}

/**
 提交工单
 */
-(void)submitOrderFormInfoAction {
    NSDictionary *templateRespDic = [templateVC onReponseTemplateValueWithCheckRequired:YES];
    if (![templateRespDic[@"code"] isEqualToString:@"0"]) return; //数据校验不成功
    NSDictionary *params = @{@"organId" : _detailModel.baseInfos.organId,
                             @"serviceOrderId" : CHECKVALUE(_detailModel.baseInfos.serviceOrderId),
                             @"trackId" : CHECKVALUE(_detailModel.baseInfos.trackId),
                             @"userId" : kAccountUserID,
                             @"actionCode" : CHECKVALUE(_actionModel.actionCode),
                             @"variables" : CHECKVALUE(templateRespDic[@"variables"]),
                             @"custId" : [SEGUtils ValueToString:[SEGProfileManager sharedManager].profile.custId]
                             };
    [SVProgressHUD show];
    [[SEGOrderDetailManager sharedManager] handleOrderWith:params finished:^(BOOL isSuccessed, id result, NSString *codeType, NSString *errorMessage) {
        [SVProgressHUD dismiss];
        if (isSuccessed) {
            /*
             4.8.0修改评价处理逻辑
             old：判断 actionModel.actionCode == ACTION_HANDLE
             new：判断 widgetType == evaluate
             */
            if([_actionModel.formList.firstObject.widgetType isEqualToString:@"evaluate"]) {//评价环节
                [self praiseForEvaluate];
                [self onFinishedAction];
            } else {
                [self onFinishedAction];
            }
        } else {
            [SEGAlertView showTmepMessageWithMessage:errorMessage];
        }
    }];
}

/**
 返回上级界面
 */
-(void)popToRootViewContorller:(id)result {
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.25 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [self.navigationController popToRootViewControllerAnimated:YES];
    });
}


/**
 处理完成跳转页面
 */
- (void)onFinishedAction {
    //处理完成通知待办列表刷新数据
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.25 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [[NSNotificationCenter defaultCenter] postNotificationName:NOTI_SEGORDERMYSERVICE_LIST_REFRESH object:nil];
        [self.navigationController popViewControllerAnimated:YES];
        
    });
}

/**
 评价环节如果评论是>=5星，分享给帮帮赞赞
 ACTION_HANDLE 评价
 */
- (void)praiseForEvaluate {
    NSInteger evaluateValue = [templateVC.evaluateValue integerValue];
    if (evaluateValue && evaluateValue > 4) {
        SEGProfileModel *sysAccount = [SEGProfileManager sharedManager].profile;
        NSDictionary* saveDict = [[NSMutableDictionary alloc] initWithObjectsAndKeys:@"", @"objId",
                                  @"11", @"objType",
                                  @"0", @"isBroadCast",
                                  [NSString stringWithFormat:@"认证住户“%@”给予社区物业服务中心【五星好评】一次。#服务你我他，品质监督靠大家#", sysAccount.nickname], @"quizContent",
                                  sysAccount.userId, @"userId",
                                  @"10010", @"quizTypeId",
                                  @"3", @"quizRangeId",
                                  sysAccount.cityId, @"regionId", //城市编码
                                  sysAccount.jobCommunity, @"organId", //小区id
                                  [NSString stringWithFormat:@"%@/h5/zanzan/szz.html?userId=%@&serviceId=%@", kClientRootURL, sysAccount.userId, CHECKVALUE(_detailModel.baseInfos.serviceOrderId)], @"linkUrl",
                                  @"物业服务", @"linkTitle",
                                  @"", @"quizPic", //图片拼接
                                  [NSString stringWithFormat:@"来自 %@",kAppName], @"communityName", //城市+名称
                                  sysAccount.nickname, @"creator", nil];
        [[SEGOrderDetailManager sharedManager] praiseForEvaluate:saveDict finished:^(BOOL isSuccessed, id result, NSString *codeType, NSString *errorMessage) {
        }];
    }
}


/**
 *  返回按钮，返回时保存填充的数据
 *
 *  @param sender 按钮实例
 */
- (void)onNavigationLeftButtonClicked:(UIButton*)sender {
    [self.navigationController popViewControllerAnimated:YES];
}

#pragma mark - ================<懒加载>===============
-(NSMutableArray *)dataArray{
    if (!_dataArray) {
        _dataArray = [[NSMutableArray alloc] init];
    }
    return _dataArray;
}

@end
